package fr.univ.lille1.server.managerimpl;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import fr.univ.lille1.server.dao.SessionKeyDao;
import fr.univ.lille1.server.dao.UserDao;
import fr.univ.lille1.server.domain.SessionKey;
import fr.univ.lille1.server.domain.User;
import fr.univ.lille1.server.domain.User.Type;
import fr.univ.lille1.server.manager.UserManager;
import fr.univ.lille1.server.utils.Utils;

@Stateless
public class UserManagerImpl implements UserManager {

	@EJB
	private UserDao userDao;
	
	@EJB
	private SessionKeyDao sessionKeyDao;

	public SessionKey createUser(String name, String password, String mail, Type userType) {
		String hashedPassword = Utils.md5(password);
		if(hashedPassword == null){
			return null;
		}
		if(!Utils.validateMail(mail)){
			return null;
		}
		User user = null;
		if(userType.equals(Type.GOOGLE)){
			user = userDao.create(new User(name, hashedPassword, mail, userType));
		}else{
			//For standard users, password can not be null
			if(password!=null){
				user = userDao.create(new User(name, hashedPassword, mail, userType));
			}
		}
		
		if(user!=null){
			sessionKeyDao.generateNewKey(user);
			return sessionKeyDao.findSessionKeyByUser(user);
		}
		
		return null;
	}

	public User updateUser(int id, String name, String password, String mail) {
		String hashedPassword = Utils.md5(password);
		if(hashedPassword == null){
			return null;
		}
		if(!Utils.validateMail(mail)){
			return null;
		}
		if(!Utils.checkString(name)){
			return null;
		}
		User user = userDao.find(id);
		if(!Utils.checkObject(user)){
			return null;
		}
		user.setName(name);
		user.setPassword(hashedPassword);
		user.setMail(mail);
		return userDao.update(user);
	}

	@Override
	public User findUserById(int id) {
		return userDao.find(id);
	}

	@Override
	public User findUserByName(String name) {
		if(!Utils.checkString(name)){
			return null;
		}
		return userDao.findByName(name);
	}

	@Override
	public User findUserByMail(String mail) {
		if(!Utils.validateMail(mail)){
			return null;
		}
		return userDao.findByMail(mail);
	}

	@Override
	public boolean login(String mail, String password) {
		String hashedPassword = Utils.md5(password);
		if(hashedPassword == null){
			return false;
		}
		User u = this.findUserByMail(mail);
		if(u == null){
			return false;
		}
		return u.getPassword().equals(hashedPassword);
	}
}
